<template>
	<view class="record-list" @click="closeModalOnClickOutside">
		<scroll-view class="scroll-view" scroll-y="true">
			<TopTabs :investigation-length="investigationLength" :finish-length="finishLength" />
			<view class="archives-main card">
				<SearchCollapse ref="SearchCollapseRef" class="search-box" :form="formData" :formNames="formNames"
					@reset="resetForm" @submit="searchConfirm">
					<template v-slot:content="{ currentKey }">
						<view>
							<scroll-view style="height: 100%;" scroll-y="true">
								<view v-if="currentKey == 'name'" class="search-input">
									<u-input v-model="formData.name" clearable @confirm="confirmInput($event, 'name')"
										placeholder="请输入案卷名称" />
								</view>
								<view v-if="currentKey == 'state'" class="drop-down-wrap">
									<SelectList :value="formData.state" @input="changeVal($event, 'state')"
										:list="archivesStateList" />
								</view>
								<view v-if="currentKey == 'archivesType'" class="drop-down-wrap">
									<SelectList :value="formData.archivesType"
										@input="changeVal($event, 'archivesType')" :list="archivesTypeList" />
								</view>
								<view v-if="currentKey == 'fireName'" class="search-input">
									<u-input v-model="formData.fireName" clearable
										@confirm="confirmInput($event, 'fireName')" placeholder="请输入起火对象" />
								</view>
								<view v-if="currentKey == 'searchCreateTime'" @click="showDatePicker">
									<DateRangeInput :value="formData.searchCreateTime" />
								</view>
							</scroll-view>
						</view>
					</template>
				</SearchCollapse>
				<view class="table-box">
					<uni-table class="table" emptyText="暂无更多数据">
						<uni-tr>
							<uni-th align="left">案卷名称</uni-th>
							<uni-th class="archives-id" align="left">案卷编号</uni-th>
							<uni-th class="archives-type" align="left">同步状态</uni-th>
							<uni-th class="archives-state" align="left">状态</uni-th>
							<uni-th class="archives-type" align="left">程序类型</uni-th>
							<uni-th class="archives-fire-name" align="left">起火对象</uni-th>
							<uni-th class="archives-time" align="left">创建时间</uni-th>
							<uni-th class="operate-btns" align="right">操作</uni-th>
						</uni-tr>
						<uni-tr v-for="(archive, index) in tableData" :key="index">
							<uni-td class="archives-name"><text @click="toDetail(archive)">{{ archive.name
							}}</text></uni-td>
							<uni-td class="archives-id">{{ archive.code || '--' }}</uni-td>
							<uni-td class="archives-type">
								<u-tag :text="syncStatusLabel(archive.syncStatus)"
									:type="syncStatusTag(archive.syncStatus)" @click="onSyncData(archive)" />
							</uni-td>
							<uni-td class="archives-state">
								<text :class="{ 'error': archiveStateError(archive.state) }">{{
									archiveStateLabel(archive.state)
								}}</text>
							</uni-td>
							<uni-td class="archives-type">
								<u-tag :text="ARCHIVES_TYPE_NAMES[archive.archivesType]"
									:type="archivesTypeTag[archive.archivesType]" />
							</uni-td>
							<uni-td class="archives-fire-name">{{ archive.fireName }}</uni-td>
							<uni-td class="archives-time">{{ archive.createTime }}</uni-td>
							<uni-td class="operate-btns">
								<view class="uni-group" v-if="archive.syncStatus != shouldCloundArchive">
									<text class="enter-btn btn" @click="toDetail(archive)">进入</text>
									<text class="del-btn btn" @click="handleDelete(archive)">删除</text>
								</view>
							</uni-td>
						</uni-tr>
						<template v-slot:empty-content>
							<view class="empty-container">
								<u-button type="primary" @click="toAddPage">前往添加案卷</u-button>
							</view>
						</template>
					</uni-table>
				</view>
				<view class="uni-pagination-box">
					<uni-pagination show-icon v-model="Page.CurrentPage" :page-size="Page.PageSize" :total="Page.Total"
						@change="pageCurrentChange" />
				</view>
			</view>
		</scroll-view>
		<u-modal v-model="delModelObj.show" :content="delModelObj.content" show-cancel-button
			@confirm="delModelConfirm"></u-modal>
		<u-modal v-model="confirmBox.show" :content="confirmBox.content" show-cancel-button
			@confirm="confirmBoxConfirm"></u-modal>
		<!-- 前往最新案件 -->
		<u-modal v-model="handleCaseTips.show" :content="handleCaseTips.content" :show-cancel-button="true"
			@confirm="handleCaseTipsConfirm" @cancel="handelCaseTipsCancel">
			<view class="slot-content">
				<view>
					<view class="content">{{ handleCaseTips.content }}</view>
					<u-checkbox v-model="handleCaseTips.checked" name="name">不再提示</u-checkbox>
				</view>
			</view>
		</u-modal>
		<!-- 同步确认提示 -->
		<u-modal v-model="syncModuleObj.show" :content="syncModuleObj.content" :show-cancel-button="true"
			@confirm="syncConfirm" @cancel="syncModuleObj.show = false"></u-modal>
		<u-calendar v-model="dateTimePickerShow" mode="range" @change="onDateConfirm"></u-calendar>
	</view>
</template>

<script>
	import {
		mapGetters
	} from "vuex"
	import TopTabs from './components/top-tabs.vue'
	import SearchCollapse from '@/components/search-collapse/search-collapse.vue'
	import SelectList from '@/components/select-list/select-list.vue'
	import DateRangeInput from '@/components/date-range-input/date-range-input.vue'
	import {
		ARCHIVES_TYPE,
		ARCHIVES_TYPE_NAMES,
		ARCHIVES_STATE,
		ARCHIVES_STATE_NAMES,
		archivesType as archivesTypeTag,
		SYNC_STATUS_TYPE,
		SYNC_STATUS_NAMES
	} from '@/const/archives';

	import {
		convertToLabelValueList
	} from '@/const/utils'
	import {
		getType
	} from '@/common/utils/common.js'

	import {
		getArchivesListByEnvironment
	} from '@/common/environmentalApi/index.js'

	import {
		removeLocalFile,
		compressZip,
		getNetworkDatatoLocal,
		copyFiles,
		createFile,
		updateArchivesTime,
	} from '@/static/common/js/padLocalFileHandler.js'
	export default {
		components: {
			TopTabs,
			SearchCollapse,
			SelectList,
			DateRangeInput
		},
		data() {
			return {
				ARCHIVES_TYPE_NAMES,
				ARCHIVES_STATE_NAMES,
				archivesTypeTag,
				headList: {
					all: {
						total: 0,
						text: '全部'
					},
					investigation: {
						total: 0,
						text: '调查中'
					},
					finish: {
						total: 0,
						text: '结案归档'
					}
				},
				formData: {
					name: null,
					state: null,
					archivesType: null,
					fireName: null,
					searchCreateTime: null,
				},
				comShow: true,
				formNames: {
					name: '案卷名称',
					state: '条件状态',
					archivesType: '程序类型',
					fireName: '起火对象 ',
					searchCreateTime: '创建时间',
				},
				first: true,
				tableData: [],
				offList: [],
				Page: {
					TotalList: [],
					PageSize: 10,
					CurrentPage: 1,
					Total: 0
				},
				investigationLength: 0,
				finishLength: 0,
				delModelObj: {
					show: false,
					content: '您确认删除此案卷吗？'
				},
				confirmBox: {
					show: false,
					content: '当前还有离线数据未同步，请立即同步'
				},
				handleCaseTips: {
					show: false,
					content: '当前系统检测到您有需要协办的案卷,是否立即前往？',
					archivesData: null,
					checked: false
				},
				dateTimePickerShow: false,
				syncModuleObj: {
					show: false,
					content: '你确认同步该案卷吗？',
					item: null
				}
			};
		},
		computed: {
			...mapGetters(['isNetworkConnected']),
			archivesStateList() {
				return convertToLabelValueList(ARCHIVES_STATE, ARCHIVES_STATE_NAMES)
			},
			archivesTypeList() {
				return convertToLabelValueList(ARCHIVES_TYPE, ARCHIVES_TYPE_NAMES)
			},
			syncStatusLabel() {
				return (syncStatus) => {
					return SYNC_STATUS_NAMES[syncStatus] || SYNC_STATUS_NAMES[SYNC_STATUS_TYPE.NOT_UPWARD_SYNCED]
				}
			},
			syncStatusTag() {
				const {
					NOT_UPWARD_SYNCED,
					PENDING_UPWARD_UPDATE,
					NOT_DOWNWARD_SYNCED,
					PENDING_DOWNWARD_UPDATE,
					SYNCED
				} = SYNC_STATUS_TYPE
				return (syncStatus) => {
					const typeMap = {
						[NOT_UPWARD_SYNCED]: 'warning',
						[PENDING_UPWARD_UPDATE]: 'error',
						[NOT_DOWNWARD_SYNCED]: 'warning',
						[PENDING_DOWNWARD_UPDATE]: 'error',
						[SYNCED]: 'success',
					}
					return typeMap[syncStatus] || 'info'
				}
			},
			archiveStateLabel() {
				return (state) => {
					return ARCHIVES_STATE_NAMES[state] || ARCHIVES_STATE_NAMES[ARCHIVES_STATE.INVESTIGATE]
				}
			},
			archiveStateError() {
				return (state) => {
					return !state || state == ARCHIVES_STATE.INVESTIGATE
				}
			},
			archivesName() {
				return archive => {
					if (archive.doPerson && archive.doOtherPerson) {
						return archive.doPerson.indexOf(this.vuex_user.nickName) != -1 || archive.doOtherPerson
							.indexOf(this.vuex_user.nickName) != -1;
					} else {
						return false;
					}
				};
			},
			syncList() {
				return this.offList.filter(item => !item.isSyn || item.isSyn === '0').map(item => item.archivesId)
			},
			// 数据从本地上传到云端
			shouldUploadToCloud() {
				const {
					NOT_UPWARD_SYNCED,
					PENDING_UPWARD_UPDATE,
					NOT_DOWNWARD_SYNCED,
					PENDING_DOWNWARD_UPDATE,
					SYNCED
				} = SYNC_STATUS_TYPE
				return [NOT_UPWARD_SYNCED, PENDING_UPWARD_UPDATE]
			},
			// 数据从云端下载到本地
			shouldDownloadFromCloud() {
				const {
					NOT_UPWARD_SYNCED,
					PENDING_UPWARD_UPDATE,
					NOT_DOWNWARD_SYNCED,
					PENDING_DOWNWARD_UPDATE,
					SYNCED
				} = SYNC_STATUS_TYPE
				return [NOT_DOWNWARD_SYNCED, PENDING_DOWNWARD_UPDATE]
			},
			shouldLocalDelete() {
				const {
					NOT_UPWARD_SYNCED,
					PENDING_UPWARD_UPDATE,
					NOT_DOWNWARD_SYNCED,
					PENDING_DOWNWARD_UPDATE,
					SYNCED
				} = SYNC_STATUS_TYPE
				return [NOT_UPWARD_SYNCED, PENDING_UPWARD_UPDATE, PENDING_DOWNWARD_UPDATE, SYNCED]
			},
			shouldCloundArchive() {
				return SYNC_STATUS_TYPE.NOT_DOWNWARD_SYNCED
			}
		},
		onLoad() {
			// this.getArchivesList()
			// copyFiles().then(() => {
			// })
		},
		onShow() {
			this.first = true
			this.getArchivesList()

		},
		methods: {
			toAddPage() {
				uni.navigateTo({
					url: '/pages/sys/archives/add'
				});
			},
			closeModalOnClickOutside(e) {
				if (this.$refs.SearchCollapseRef.collapseBodyShow) {
					this.$refs.SearchCollapseRef.collapseBodyShow = false
				}
			},
			confirmInput(val, key) {
				this.formData[key] == val
				this.searchConfirm(this.formData)
			},
			changeVal(val, key) {
				this.formData[key] = this.formData[key] === val ? null : val
				this.searchConfirm(this.formData)
			},
			searchConfirm(params) {
				this.getArchivesList(params);
			},
			async getArchivesList(params, refresh = false) {
				uni.showLoading({
					title: '加载中'
				});
				let remoteArchivesList = !this.isNetworkConnected ? this.vuex_basicData.remoteArchivesList : []
				let list = await getArchivesListByEnvironment(params, refresh, remoteArchivesList)
				let investigationArr = list.filter(item => {
					return !item.state || item.state == ARCHIVES_STATE.INVESTIGATE
				})
				let finishArr = list.filter(item => {
					return item.state == ARCHIVES_STATE.CLOSECASE
				})
				if (this.first) {
					this.investigationLength = investigationArr.length
					this.finishLength = finishArr.length
					this.first = false
				}

				let TotalList = this.Page.TotalList = list
				let arr = TotalList
				if (getType(params) != "object") {
					arr = TotalList
				}
				this.sliceList(arr)
				uni.hideLoading();
			},
			sliceList(arr) {
				this.Page.CurrentPage = 1
				this.Page.Total = arr.length
				if (arr.length > this.Page.PageSize) {
					this.tableData = arr.slice(0, this.Page.PageSize)
				} else {
					this.tableData = arr
				}
			},
			showDatePicker() {
				this.dateTimePickerShow = true
			},
			onDateConfirm(dateOParams) {
				const {
					startDate,
					endDate
				} = dateOParams
				this.dateTimePickerShow = false
				this.formData.searchCreateTime = [startDate, endDate]
				this.searchConfirm(this.formData)
			},
			resetForm() {
				this.formData = this.$options.data().formData
				this.getArchivesList(this.formData, true)
			},
			onSyncData(archive) {
				this.syncModuleObj.show = true
				this.syncModuleObj.item = archive
			},
			async syncConfirm() {
				let archive = this.syncModuleObj.item
				if (this.isNetworkConnected) {
					// uni.showLoading({
					// 	title: '同步中',
					// 	mask: true
					// })

					if (this.shouldUploadToCloud.includes(archive.syncStatus)) {
						console.log('更新案卷的操作时间');
						// await updateArchivesTime(archive.archivesId, this.$u.timeFormat(new Date(),
						// 	'yyyy-mm-dd hh:MM:ss'))
						// 更新案卷的操作时间 
						archive.pullUpdateTime = archive.pushUpdateTime = archive.updateTime = this.$u.timeFormat(
							new Date(),
							'yyyy-mm-dd hh:MM:ss')
						await createFile(archive)
						console.log('compressZip before');
						compressZip(archive.archivesId, this.vuex_user.userId).then(() => {
							console.log('compressZip then');
							uni.hideLoading()
							console.log('compressZip then');
							this.getArchivesList({}, true)
						}).catch((err) => {
							uni.hideLoading()
							console.error(err)
						})
					} else if (this.shouldDownloadFromCloud.includes(archive.syncStatus)) {
						getNetworkDatatoLocal(archive.archivesId).then(async (archiveData) => {
							
							archiveData.pullUpdateTime = archiveData.pushUpdateTime = archiveData
								.updateTime = this.$u
								.timeFormat(new Date(),
									'yyyy-mm-dd hh:MM:ss')
							await createFile(archiveData)
							uni.hideLoading()
							this.getArchivesList({}, true)
						}).catch((err) => {
							uni.hideLoading()
							console.error(err)
						})
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: '请连接网络并重新登录后再同步'
					})
				}
			},
			toDetail(data) {
				if (data.syncStatus == this.shouldCloundArchive) {
					return uni.showToast({
						title: "该案卷为云端案卷，暂不支持查看",
						icon: 'none'
					})
				}
				this.$u.vuex('vuex_archives', data);
				uni.$emit('archivesId', data.archivesId);
				uni.setStorage({
					key: 'archivesId',
					data: data.archivesId
				});

				uni.navigateTo({
					url: `/pages/sys/detail/index?archivesId=${data.archivesId}`
				});
			},
			handleDelete(item) {
				this.delModelObj.show = true;
				this.currentItem = item;
			},
			delModelConfirm() {
				const {
					syncStatus
				} = this.currentItem
				if (this.shouldLocalDelete.includes(syncStatus)) {
					removeLocalFile(this.currentItem.archivesId).then(() => {
						this.getArchivesList({}, true);
					})
				} else {
					this.$u.api.archives.remove(this.currentItem.archivesId).then(res => {
						if (res.code == 200) {
							this.getArchivesList({}, true);
							if (this.currentItem.archivesId == this.vuex_archives.archivesId) {
								this.$u.vuex('vuex_archives', {});
								uni.$emit('archivesId', null);
								uni.setStorage({
									key: 'archivesId',
									data: null
								});
							}

							uni.showToast({
								title: res.msg,
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'error'
							});
						}
					});
				}
			},
			confirmBoxConfirm() {},
			pageCurrentChange(e) {
				let current = e.current
				const end = current * this.Page.PageSize
				const start = end - this.Page.PageSize
				let TotalList = this.Page.TotalList
				let arr = TotalList
				this.tableData = arr.slice(start, end)
			},
			handleCaseTipsConfirm() {
				uni.setStorage({
					key: 'handleCaseTipsChecked-' + this.vuex_user.userId,
					data: {
						userId: this.vuex_user.userId,
						checked: this.handleCaseTips.checked
					},
					success: function() {}
				});

				const data = this.handleCaseTips.archivesData;
				this.$u.vuex('vuex_archives', data);
				uni.$emit('archivesId', data?.archivesId || null);
				return
				uni.switchTab({
					url: `/pages/sys/detail/index`
				});
			},
			handelCaseTipsCancel() {
				this.handleCaseTips.checked = false;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.record-list {
		padding: 40upx;
		background-color: $u-bg-color;
		height: 100vh;
		overflow: hidden;
		/* #ifdef H5 */
		height: calc(100vh - 44px); // 顶部标题 与 底部导航 的高度总和是 94px

		/* #endif */

		.archives-main {
			padding: 24rpx 0 0;

			.search-box {
				// padding: 0 30rpx;
				margin-bottom: 32rpx;
			}
		}

		.scroll-view {
			height: 100%;
			overflow-y: auto;
		}

		.search-box {
			.search-input {
				background-color: #fff;
				width: 100%;
				padding: 16rpx 34rpx;
				border-radius: 4px;
				font-size: 28rpx;
			}
		}


		.table-box {
			// margin: 0 -40rpx;

			margin-bottom: 30rpx;
			background-color: #fff;

			.empty-container {
				position: absolute;
				right: 0;
				left: 0;
				width: 400rpx;
				margin: 0 auto;
				padding: 20rpx 0;
			}

			.uni-group {
				display: flex;
				align-items: center;
				justify-content: center;

				.uni-button {
					font-size: 14px;
				}
			}

			/deep/ .uni-table {

				.uni-table-tr {

					// padding: 0 54rpx;
					.uni-table-td:first-child,
					.uni-table-th:first-child {
						padding-left: 54rpx;
					}
				}

				.uni-table-tr:first-child {
					background-color: #F2F3F5;
				}
			}

			.active {
				color: #67c23a;
			}

			.table {

				.operate-btns {
					// width: 290rpx;

					.btn {
						color: #1B7DD4;
						font-size: 28rpx;

						&.del-btn {
							margin-left: 44rpx;
						}
					}
				}

				.archives-name {
					color: #1B7DD4;
					text-decoration: underline;
				}

				.archives-id {
					// min-width: 152rpx;
				}

				.archives-state {
					// min-width: 160rpx;

					text {
						color: $u-type-success;
					}

					.error {
						color: $u-type-error;
					}
				}

				.archives-type {
					// min-width: 188rpx;
				}

				.archives-time {
					// min-width: 316rpx;
				}

				.archives-fire-name {
					// min-width: 188rpx;
				}
			}
		}

		.uni-pagination-box {
			padding: 0 20rpx 20rpx 0;
			display: flex;
			justify-content: flex-end;

			/deep/ .uni-pagination__num-tag {
				cursor: pointer;
				min-width: 30px;
				width: 30px !important;
				margin: 0 5px;
				height: 30px;
				text-align: center;
				line-height: 30px;
				color: #999;
				border-radius: 4px;
			}

			/deep/ .page--active {
				color: #ffffff;
			}
		}
	}

	.slot-content {
		&>view {
			padding: 40upx;

			.content {
				margin-bottom: 20upx;
			}
		}
	}
</style>